package com.gmrz.uap.servlet;

import com.gmrz.uap.entity.Tenant;
import com.gmrz.uap.service.TenantService;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Wang Haifeng
 */
@Singleton
public class SystemServlet extends HttpServlet {

    private static final Logger log = LoggerFactory.getLogger(SystemServlet.class);

    private final TenantService tenantService;

    @Inject
    public SystemServlet(TenantService tenantService) {
        this.tenantService = tenantService;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.info("SystemServlet doGet");
        resp.getWriter().write("SystemServlet doGet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            //guice-servlet获取请求中的POST报文
            log.info("SystemServlet doPost");

            String requestBody = req.getReader().lines().reduce("", (accumulator, actual) -> accumulator + actual);
            log.info("body:{}", requestBody);

            Tenant tenant = new Tenant();
            tenant.setTenantId("1103");
            String rows = tenantService.getAllTenant(tenant, requestBody);
            log.info("tenants:{}", rows);

            if (rows.contains("500")) {
                resp.setStatus(500);
            }

            resp.getWriter().write(rows);
        } catch (Exception e) {
            log.error("SystemServlet doPost error", e);
        }
    }
}
